package com.lxy.aimin.auth.service;

import cn.hutool.json.JSONUtil;
import com.lxy.aimin.auth.wx.constant.WxApiUrlConstants;
import com.lxy.aimin.auth.wx.pojo.Jscode2sessionResult;
import com.lxy.aimin.auth.wx.properties.WXProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;


@Service
public class WxService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    WXProperties wxProperties;


    public void wxLogin(String code){
        Map<String,String> params = new HashMap<>();
        params.put("appid",wxProperties.getAppid());
        params.put("secret",wxProperties.getSecret());
        params.put("js_code",code);
        params.put("grant_type","authorization_code");

        //完整url
        String url = UriComponentsBuilder.fromUriString(WxApiUrlConstants.Miniprogram.DO_LOGIN_URL)
                .queryParam("appid", params.get("appid"))
                .queryParam("secret", params.get("secret"))
                .queryParam("js_code", params.get("js_code"))
                .queryParam("grant_type", params.get("grant_type"))
                .toUriString();
        String response = restTemplate.getForObject(url,String.class);
        Jscode2sessionResult jscode2sessionResult = JSONUtil.toBean(response, Jscode2sessionResult.class);
        System.out.println(jscode2sessionResult.getOpenid());

    }
}
